package com.fuego.creditsystemuser.controller;


import cn.hutool.core.bean.BeanUtil;
import com.fuego.creditsystemuser.service.IUserInfoService;
import com.fuego.creditsystemuser.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.LoginFormDTO;
import org.example.dto.Result;
import org.example.dto.UserDTO;
import org.example.entity.User;
import org.example.entity.UserInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone) {
        // TODO 发送短信验证码并保存验证码

        try {
            // 现有逻辑
            return userService.sendCode(phone);
        } catch (Exception e) {
            log.error("Error in sendCode: {}", e.getMessage(), e);
            return Result.fail("Failed to send code: " + e.getMessage());
        }

    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm){
        // 实现登录功能

        return userService.login(loginForm);
    }
    @GetMapping("/status")
    public Result getVerificationStatus(HttpServletRequest request) {
        Long userId = userService.getIdByToken(request);
        if (userId == null) {
            return Result.fail("用户未登录");
        }
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo != null) {
            return Result.ok(userInfo);
        }
        return Result.fail("未实名认证");
    }
    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && !token.isEmpty()) {
            stringRedisTemplate.delete("login:token:" + token);
        }
        return Result.ok("登出成功");
    }

    @GetMapping("/me")
    public Result me(HttpServletRequest request) {
        //  获取当前登录的用户并返回
        User user= userService.getById(userService.getIdByToken(request));

        return Result.ok(user);
    }

    @GetMapping("/basic")
    public Result basic(HttpServletRequest request) {
        Long userId= userService.getIdByToken(request);
        User user =userService.getById(userId);

        return Result.ok(user);
    }


    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        // 查询详情
        UserInfo info = userInfoService.getById(userService.getIdByToken(request));
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        // 返回
        return Result.ok(info);
    }
    @GetMapping("{id}")
    public Result queryUserById(@PathVariable("id") Long userId){
        // 查询详情
        User user = userService.getById(userId);
        if (user == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        UserDTO userDTO= BeanUtil.copyProperties(user,UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public Result updateUser(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.fail("用户ID不能为空");
        }
        // 验证输入字段
        if (user.getEmail() != null && !user.getEmail().matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
            return Result.fail("无效的邮箱格式");
        }
        if (user.getNickName() != null && (user.getNickName().length() < 2 || user.getNickName().length() > 20)) {
            return Result.fail("昵称长度必须在2到20个字符之间");
        }
        // 只更新非空的字段
        User existingUser = userService.getById(user.getId());
        if (existingUser == null) {
            return Result.fail("用户不存在");
        }
        if (user.getEmail() != null) {
            existingUser.setEmail(user.getEmail());
        }
        if (user.getNickName() != null) {
            existingUser.setNickName(user.getNickName());
        }
        if (user.getIcon() != null) {
            existingUser.setIcon(user.getIcon());
        }
        existingUser.setAge(user.getAge());
            existingUser.setGender(user.getGender());
            existingUser.setJob(user.getJob());
            existingUser.setIncome(user.getIncome());
            existingUser.setAddress(user.getAddress());

        // 更新数据库
        boolean updated = userService.updateById(existingUser);
        return updated ? Result.ok() : Result.fail("更新失败");
    }
    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }

    @GetMapping ("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }


}
